package com.edu.whu.service.impl;

import com.edu.whu.dao.ContentJpaRepository;
import com.edu.whu.entity.Content;
import com.edu.whu.entity.UserInfo;
import com.edu.whu.service.ContentService;
import com.edu.whu.service.ServiceException;
import com.edu.whu.service.TokenUserService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ContentServiceImpl implements ContentService {
    private final ContentJpaRepository contentJpaRepository;
    private final TokenUserService tokenUserService;

    public ContentServiceImpl(ContentJpaRepository contentJpaRepository, TokenUserService tokenUserService) {
        this.contentJpaRepository = contentJpaRepository;
        this.tokenUserService = tokenUserService;
    }

    @Override
    public List<Content> getAllContent() {
        return contentJpaRepository.findAll();
    }

    @Override
    public Content postContent(String token, Content content) throws ServiceException {
        long date = System.currentTimeMillis() / 1000;
        UserInfo userInfo = tokenUserService.checkToken(token);
        String author = userInfo.getAccount();
        content.setAuthor(author);
        content.setDate(date);
        return contentJpaRepository.save(content);
    }

    @Override
    public void deleteContent(String token, Integer contentId) throws ServiceException {
        Content content = contentJpaRepository.findById(contentId).orElse(null);
        if (content == null) {
            throw new ServiceException("指定内容不存在");
        }
        UserInfo userInfo = tokenUserService.checkToken(token);
        if (content.getAuthor().equals(userInfo.getName())) {
            contentJpaRepository.deleteById(contentId);
        } else {
            throw new ServiceException("不是自己的内容");
        }
    }

    @Override
    public Content getContent(Integer id) throws ServiceException {
        Content content = contentJpaRepository.findById(id).orElse(null);
        if (content == null) {
            throw new ServiceException("指定内容不存在");
        } else {
            return content;
        }
    }
}
